package com.star.cat.common.parse;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.star.cat.common.utils.ReflectionUtil;

/**
 * 默认key解析器
 * 
 * @author liguangcai
 * @date 2018/08/29 14:31
 */
@SuppressWarnings("serial")
@Service
public class DefaultKeyParse extends KeyParse {

	/**
	 * 原key:
	 * key=star_cat_user:[1.userName#1.status]
	 * 构建后：
	 * key=star_cat_user:admin:lock
	 * 构建出的key后面是以":"分割，前面是自定义的前缀
	 */
	@Override
	public String buildKey(String key, Class<?>[] paramClasses, Object[] params) {
		String keyHeader = StringUtils.substringBefore(key, "[");
		String keyBody = StringUtils.substringBetween(key, "[", "]");
		String[] keyParams = keyBody.split(SPLIT);
		StringBuilder sb = new StringBuilder(keyHeader + "");
		if (keyParams.length > 0) {
			for (String keyParam : keyParams) {
				String[] exps = keyParam.split("\\.");
				int index = Integer.valueOf(exps[0]) - 1;
				Object value = params[index]; // 取出参数
				if (paramClasses[index].isAssignableFrom(List.class)) { // 参数类型是否是List类型
					List<?> list = (List<?>) params[index];
					value = list.size() > 0 ? list.get(0) : ""; // 集合默认取第一个
				}
				if (null == value || "null".equals(value)) {
					value = "";
				}
				if (exps.length > 1) { // 说明是对象，要取对象字段值
					value = ReflectionUtil.getFieldValue(value, exps[1]);
				}
				sb.append(value.toString() + ":");
			}
		}
		return sb.toString().substring(0, sb.toString().length() - 1);
	}

}
